using Catalog.Application.Brands.Commands;
using Catalog.Application.Brands.Interfaces;
using Catalog.Application.CatalogItems.Interfaces;
using Catalog.Application.Interfaces;
using MediatR;

namespace Catalog.Application.Brands.CommandHandlers;

public class DeleteBrandCommandHandler : IRequestHandler<DeleteBrandCommand, Unit>
{
    private readonly IBrandRepository _brandRepository;
    private readonly ICatalogItemReadService _catalogItemReadService;
    private readonly IUnitOfWork _unitOfWork;
    public DeleteBrandCommandHandler(IBrandRepository brandRepository, ICatalogItemReadService catalogItemReadService, IUnitOfWork unitOfWork)
    {
        _brandRepository = brandRepository;
        _catalogItemReadService = catalogItemReadService;
        _unitOfWork = unitOfWork;
    }
    public async Task<Unit> Handle(DeleteBrandCommand request, CancellationToken cancellationToken)
    {
        var brand = await _brandRepository.GetByIdAsync(request.id);
        if (brand == null)
            throw new KeyNotFoundException("品牌不存在！");
        var hasItems = await _catalogItemReadService.ExistsByBrandIdAsync(request.id);
        if (hasItems)
            throw new KeyNotFoundException("该品牌仍被商品引用，不能删除");

        _brandRepository.Remove(brand);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}